//
//  WBRefreshControl.swift
//  Weobo
//
//  Created by 史亚洲 on 16/1/20.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SnapKit

//自定义枚举,各个阶段的状态
enum WBRefreshStatue: Int {

    //普通状态
    case Normal = 1
    
    //下拉等待刷新状态
    case Pulling = 2
    
    
    //上拉加载更多状态
    case Refreshing = 3


}

//自定义下拉刷新控件,正对UIScrollView及其子类对象

private let RefreshHeight: CGFloat = 60
class WBRefreshControl: UIControl {
    
    //定义属性,用来记录上一次的刷新状态
    var oldStatue: WBRefreshStatue = .Normal

    
    //MARK:定义外部变量
    var statue: WBRefreshStatue = .Normal {
        didSet {
            //根据状态,修改UI状态
            switch statue {
            case .Normal:
                    //修改文案
                tipLabel.text="下拉起飞"
                //动画效果
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowIcon.transform=CGAffineTransformIdentity
                    })
                
                //显示箭头
                arrowIcon.hidden=false
                //关闭动画
                indicatorView.stopAnimating()
                
                
                //必须是刷新状态,减去RefreshHeight
                if oldStatue == .Refreshing {
                    
                    //修改scrollView的1contentInset
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        var inset = self.scrollView!.contentInset
                        //顶部加上刷新控件的高度
                        inset.top -= RefreshHeight
                        
                        //修改
                        self.scrollView?.contentInset=inset
                        
                        })
                }
                
            case .Pulling:
                tipLabel.text="准备起飞"
                
                //改变箭头的发方向
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowIcon.transform=CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
                
                
            case .Refreshing:
                tipLabel.text="正在起飞"
                
                //隐藏箭头
                arrowIcon.hidden=true
                
                //小菊花开始转动
                indicatorView.startAnimating()
                
                //执行刷新数据的操作,模拟一个valueChanged事件类型
                sendActionsForControlEvents(.ValueChanged)
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    var inset=self.scrollView!.contentInset
                    
                    inset.top += RefreshHeight
                    
                    self.scrollView?.contentInset=inset
                })
                    
            
            }
            
            //记录上一次的刷新状态
           oldStatue = statue
        }
    }
    
    //找到自定义入口
    override init(frame: CGRect) {
        let rect = CGRect(x: 0, y: -RefreshHeight, width: KWidth, height: RefreshHeight)
        
        super.init(frame: rect)
        
        //设置颜色
        backgroundColor=UIColor.orangeColor()
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //KVO监听方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        //查看该变量
//        print(change)
//        print(self.scrollView?.frame)
//        print(self.scrollView?.contentOffset)
//        print(self.scrollView?.contentInset)
        
        //1.获取滚动的改变状态的临界值
        let condationValue = -((self.scrollView?.contentInset.top ?? 0) + RefreshHeight)
        
        //2.获取滚动视图的位移
        let offsetY=self.scrollView?.contentOffset.y ?? 0

        //3.比较  临界值和位移  来改变状态
        //print(condationValue,offsetY)
        //获取正在刷新的状态,超出临界值并且松手(dragging)
        if scrollView!.dragging {
            //3.1正在被拽动
            if statue == .Normal && condationValue > offsetY {
                print("等待刷新状态")
                statue = .Pulling
      
            }else if statue == .Pulling && condationValue < offsetY {
                print("普通状态")
                statue = .Normal
            }
        }else {
        
            //松手 && 满足 准备刷新的状态
            if statue == .Pulling{
                print("正在刷新")
                statue = .Refreshing
            }
        
        }
        
        
        
    }
    //修改Normal状态,终止刷新状态
    func endRefreshing() {
        
        //延时
     let delta = dispatch_time(DISPATCH_TIME_NOW,Int64(Double(NSEC_PER_SEC) * 0.3))
        dispatch_after(delta, dispatch_get_main_queue()) { () -> Void in
            self.statue = .Normal
        }
    
    }
    override func willMoveToSuperview(newSuperview: UIView?) {
        if let mySuper = newSuperview as? UIScrollView {
        
            //记录父视图
            print("是scrollView")
            scrollView=mySuper
            
            //观察父视图的contentOffset属性
            scrollView?.addObserver(self, forKeyPath: "contentOffset", options:
                .New, context: nil)
            
        
        }
    }
    
    //移除KVO监听者
    deinit {
    scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    
    }
    
    private var scrollView: UIScrollView?
    
    //设置UI界面
    private func setupUI() {
        addSubview(backImageView)
        addSubview(tipLabel)
        addSubview(arrowIcon)
        addSubview(indicatorView)
        
        backImageView.snp_makeConstraints { (make) -> Void in
            make.bottom.left.right.equalTo(self)
            
        }
        
        tipLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_centerX).offset(15)
            make.centerY.equalTo(self.snp_centerY)
        }
        
        arrowIcon.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(tipLabel.snp_centerY)
            make.right.equalTo(tipLabel.snp_left).offset(10)
        }
        indicatorView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowIcon.snp_center)
        }
        
        
        
        
    }
    //MARK:懒加载子视图
    //1.文本
    private lazy var tipLabel: UILabel = UILabel(title: "下拉刷新", fontSize: 14, color: UIColor.blueColor())
    
    
    //2.箭头
    private lazy var arrowIcon: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    
    //3.小菊花
    private lazy var indicatorView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
    
    //4.背景图片
    private lazy var backImageView: UIImageView = UIImageView(image: UIImage(named: "refreshbg"))
    

}
